package com.gis.biz.controller;


import com.alibaba.fastjson.JSONObject;
import com.gis.common.model.ApiResult;
import com.gis.common.property.FileProperties;
import com.gis.utils.*;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

@CrossOrigin
@Api(tags = "tools")
@RestController
@RequestMapping("/biz/data-process")
public class DataProcessController {
    @Autowired
    private FileProperties fileProperties;

    @PostMapping("/dxfToGeoJSON")
    public ApiResult<Object> dxfToGeoJSON(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException, InterruptedException {
        Path fileStorageLocation = Paths.get(fileProperties.getStoreFileUrl()).toAbsolutePath().normalize();
        Path fileOutLocation = Paths.get(fileProperties.getOutFileUrl()).toAbsolutePath().normalize();
        String name =  GISFileUtils.storeFile(file, fileStorageLocation);
        String inPath = fileStorageLocation.resolve(name).toString();
        String outPath = fileOutLocation.resolve( BaseUtil.trimFileSuffix(name)+ ".json").toString();
        GDALUtils.geoTransfer(inPath,outPath,"GeoJSON");
        return ResultUtils.Success(JSONObject.parse(GISFileUtils.readFileContent(outPath)));
    }

    @PostMapping("/shpToGeoJSON")
    public ApiResult<Object> shpToGeoJSON(@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        if(!BaseUtil.getFileSuffix(file.getOriginalFilename()).equals("zip")) return ResultUtils.Success("上传格式错误，清上传zip");
        Path fileOutLocation = Paths.get(fileProperties.getOutFileUrl()).toAbsolutePath().normalize();
        Path fileStorageLocation = Paths.get(fileProperties.getStoreFileUrl()).toAbsolutePath().normalize();
        String name =  GISFileUtils.storeFile(file, fileStorageLocation);
        String zipPath = fileStorageLocation.resolve(name).toString();
        String shpName = ZipUtils.getShpZipContentName(zipPath);
        ZipUtils.ZipUncompress(zipPath,fileStorageLocation.toString());
        String outPath = fileOutLocation.resolve( BaseUtil.trimFileSuffix(name)+ ".json").toString();
        GDALUtils.geoTransfer(fileStorageLocation.resolve(shpName + ".shp").toString(),outPath,"GeoJSON");
        String res  = GISFileUtils.readFileContent(outPath);
        return ResultUtils.Success(JSONObject.parse(res));
    }

}
